package com.source.lightfowl.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.source.lightfowl.VO.PersonVO;
import com.source.lightfowl.constant.SessionKey;
import com.source.lightfowl.person.entity.Url;
import com.source.lightfowl.person.entity.UsersExtends;
import com.source.lightfowl.utils.MyResult;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xcy
 * @Date:Create：in 2020/9/11 20:19
 * @Description: 后由Faink更改，未完成
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中获取key 获取得到说明登陆成功 放行  获取为空说明没有登陆  重定向回登陆页面
        //Person user = (Person)request.getSession().getAttribute(USER_SESSION_KEY);
        System.out.println("========= preHandle =========");
        Object attribute = request.getSession().getAttribute(SessionKey.USERSEXTENDS_SESSION_KEY);
        if (null == attribute) {
            //重定向到登陆页面
            response.sendRedirect("/login.html");
            return false;
        }
        UsersExtends usersExtends =(UsersExtends) attribute;
        PersonVO user = usersExtends.getUser();
        String role  = user.getRole();
        //if (role.equals("超级管理员")) return true;

        String uri = request.getRequestURI();//无法获取当前访问的页面文件名
        int index = uri.lastIndexOf("/");

        //请求头放要访问的静态资源名字
        String authorization = request.getHeader("Authorization");
        String lastUri="";
        if (authorization != null && "".equals(authorization)) {
            if (authorization.startsWith("Bearer "))
                lastUri = authorization.substring(7);
            System.out.println(lastUri);
        } else {
            System.out.println("=========== authorization = null ============");
            return false;
        }
        if (user != null){
            List<Url> urls = usersExtends.getUrls();
            if (urls != null) {
                for (Url url : urls) {
                    if (lastUri.equals(url.getUrlname())) return true;
                }
                return false;
            } else if (!lastUri.equals("/login.html")){
                MyResult result = MyResult.build(403, "无操作权限");
                write(request, response, JSONObject.toJSONString(result));
                return false;
            }
            return true;
        }else {
            //信息不存在 未登陆
            /*String requestURI = request.getRequestURI();
            System.out.println("未登陆.开始重定向到登陆页面"+requestURI);
            response.sendRedirect("/login.html");*/
            String requestURI = request.getRequestURI();
            System.out.println("未登陆.开始重定向到登陆页面"+requestURI);
            //重定向到登陆页面
            response.sendRedirect("/login.html");
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


    }

    /**
     * 通过response返回错误信息给前端
     * @param request
     * @param response
     * @param content
     * @throws IOException
     */
    private void write(HttpServletRequest request, HttpServletResponse response, String content)
            throws IOException {

        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(content);
    }
}


